package com.book.controller.system;

import com.book.core.domain.SysMenu;
import com.book.core.dto.SysRoleSaveDTO;
import com.book.core.mode.R;
import com.book.core.query.SysMenuQuery;
import com.book.core.util.LoginUserUtil;
import com.book.core.vo.SysMenuVO;
import com.book.service.SysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/system/menu")
public class SysMenuController {
    private final SysMenuService sysMenuService;

    @GetMapping("/tree/list")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public R<List<SysMenuVO>> getMenuTreeList(SysMenuQuery query) {
        LoginUserUtil.debugAuth();
        List<SysMenuVO> menuTreeLi = sysMenuService.getMenuTreeList(query);
        return R.ok(menuTreeLi);
    }

    @GetMapping("/tree/list/parent-menu")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public R<List<SysMenuVO>> getParentMenuList() {
        List<SysMenuVO> menuTreeLi = sysMenuService.getParentMenuList();
        return R.ok(menuTreeLi);
    }

    @GetMapping("/list/by/role/{roleId}")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public R<List<SysMenu>> getMenuListByRoleId(@PathVariable Integer roleId) {
        List<SysMenu> menuTreeLi = sysMenuService.getMenuListByRoleId(roleId);
        return R.ok(menuTreeLi);
    }

    @PostMapping
    @PreAuthorize("hasAuthority('system:menu:create')")
    public R<String> saveMenu(@RequestBody @Validated SysMenu sysMenu) {
        sysMenu.setCreateTime(LocalDateTime.now());
        sysMenu.setCreatorId(LoginUserUtil.getUserId());
        sysMenuService.save(sysMenu);
        return R.ok("新增成功", null);
    }

    @PutMapping
    @PreAuthorize("hasAuthority('system:menu:update')")
    public R<String> updateMenu(@RequestBody @Validated SysMenu sysMenu) {
        sysMenu.setUpdateTime(LocalDateTime.now());
        sysMenuService.updateById(sysMenu);
        return R.ok("修改成功", null);
    }

    @DeleteMapping("/{id}")
    public R<String> deleteMenu(@PathVariable Integer id) {
        sysMenuService.removeById(id);
        return R.ok("删除成功", null);
    }

    @RequestMapping("/role/save")
    public R<Void> saveMenuRole(@RequestBody @Validated SysRoleSaveDTO sysMenuRoleDTO) {
        sysMenuService.saveMenuRole(sysMenuRoleDTO);
        return R.ok("保存成功", null);
    }
}
